// 消息系统测试工具
import { supabase } from '../lib/supabase'

export interface TestMessage {
  type: 'system' | 'comment_reply' | 'movie_upload' | 'like' | 'follow'
  title: string
  content: string
  related_movie_id?: number
  related_comment_id?: number
}

// 测试消息模板
export const testMessages: TestMessage[] = [
  {
    type: 'system',
    title: '系统维护通知',
    content: '系统将于今晚进行维护，预计持续2小时。期间可能无法正常访问，请提前做好准备。'
  },
  {
    type: 'comment_reply',
    title: '新回复',
    content: '用户回复了你的评论："这部电影真的很棒！剧情紧凑，演员表演出色。"',
    related_movie_id: 1
  },
  {
    type: 'movie_upload',
    title: '电影上传成功',
    content: '恭喜！你的电影《测试电影》已成功上传并发布。现在其他用户可以观看和评论了。',
    related_movie_id: 1
  },
  {
    type: 'like',
    title: '收到点赞',
    content: '用户点赞了你的评论："非常精彩的电影，值得推荐！"',
    related_movie_id: 1
  },
  {
    type: 'follow',
    title: '新关注者',
    content: '用户关注了你。现在他们可以看到你上传的电影和评论了。'
  }
]

// 创建测试消息
export const createTestMessage = async (message: TestMessage, recipientId: string) => {
  try {
    const { data, error } = await supabase.rpc('create_message', {
      p_recipient_id: recipientId,
      p_sender_id: null, // 系统消息
      p_type: message.type,
      p_title: message.title,
      p_content: message.content,
      p_related_movie_id: message.related_movie_id || null,
      p_related_comment_id: message.related_comment_id || null
    })

    if (error) {
      console.error('Error creating test message:', error)
      return { success: false, error: error.message }
    }

    return { success: true, data }
  } catch (error) {
    console.error('Error creating test message:', error)
    return { success: false, error: '创建测试消息失败' }
  }
}

// 批量创建测试消息
export const createBatchTestMessages = async (recipientId: string, count: number = 5) => {
  const results = []
  
  for (let i = 0; i < count; i++) {
    const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)]
    const result = await createTestMessage(randomMessage, recipientId)
    results.push(result)
    
    // 添加延迟避免过快请求
    await new Promise(resolve => setTimeout(resolve, 100))
  }
  
  return results
}

// 清理测试消息
export const cleanupTestMessages = async (recipientId: string) => {
  try {
    const { error } = await supabase
      .from('messages')
      .delete()
      .eq('recipient_id', recipientId)
      .like('title', '%测试%')

    if (error) {
      console.error('Error cleaning up test messages:', error)
      return { success: false, error: error.message }
    }

    return { success: true }
  } catch (error) {
    console.error('Error cleaning up test messages:', error)
    return { success: false, error: '清理测试消息失败' }
  }
}

// 检查消息系统状态
export const checkMessageSystemStatus = async () => {
  try {
    // 检查messages表
    const { data: messagesData, error: messagesError } = await supabase
      .from('messages')
      .select('count')
      .limit(1)

    // 检查message_settings表
    const { data: settingsData, error: settingsError } = await supabase
      .from('message_settings')
      .select('count')
      .limit(1)

    // 检查函数是否存在
    const { data: functionsData, error: functionsError } = await supabase.rpc('get_unread_message_count')

    return {
      messagesTable: !messagesError,
      settingsTable: !settingsError,
      functions: !functionsError,
      errors: {
        messages: messagesError?.message,
        settings: settingsError?.message,
        functions: functionsError?.message
      }
    }
  } catch (error) {
    console.error('Error checking message system status:', error)
    return {
      messagesTable: false,
      settingsTable: false,
      functions: false,
      errors: {
        general: '检查失败'
      }
    }
  }
}

// 获取当前用户ID
export const getCurrentUserId = async () => {
  try {
    const { data: { user } } = await supabase.auth.getUser()
    return user?.id
  } catch (error) {
    console.error('Error getting current user:', error)
    return null
  }
}

// 运行完整测试
export const runMessageSystemTest = async () => {
  console.log('开始消息系统测试...')
  
  // 1. 检查系统状态
  const status = await checkMessageSystemStatus()
  console.log('系统状态:', status)
  
  if (!status.messagesTable || !status.settingsTable || !status.functions) {
    console.error('消息系统未正确配置')
    return { success: false, error: '系统配置不完整' }
  }
  
  // 2. 获取当前用户
  const userId = await getCurrentUserId()
  if (!userId) {
    console.error('用户未登录')
    return { success: false, error: '用户未登录' }
  }
  
  // 3. 创建测试消息
  console.log('创建测试消息...')
  const results = await createBatchTestMessages(userId, 3)
  
  const successCount = results.filter(r => r.success).length
  console.log(`成功创建 ${successCount}/${results.length} 条测试消息`)
  
  return {
    success: successCount > 0,
    created: successCount,
    total: results.length,
    status
  }
}

